package com.simple.base.common.shiro;

import com.alibaba.fastjson.JSON;
import com.simple.base.common.utils.JWTUtils;
import com.simple.base.core.repository.entity.SysUser;
import com.simple.base.core.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 认证
 *
 * @author kin
 * @since 2017/12/22
 */
@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = JWTUtils.getUsername(principals.toString());
        SysUser user = JSON.parseObject(username, SysUser.class);

        if (user == null) {
            return null;
        }
        //用户权限列表
        Set<String> permsSet = sysUserService.getPermission(user.getId());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String accessToken = (String) auth.getCredentials();
        // 解密获得username，用于和数据库进行对比
        String username = JWTUtils.getUsername(accessToken);
        SysUser user = JSON.parseObject(username, SysUser.class);

        //查询用户信息
        user = sysUserService.selectById(user.getId());

        if (user == null || !JWTUtils.verify(accessToken, username, user.getPassword())) {
            throw new AuthenticationException("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == 2) {
            throw new LockedAccountException("账号已被冻结,请联系管理员");
        }

        return new SimpleAuthenticationInfo(accessToken, accessToken, getName());
    }
}
